#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>
#include <vector>

pthread_mutex_t glock=PTHREAD_MUTEX_INITIALIZER;;
pthread_cond_t gcond=PTHREAD_COND_INITIALIZER;

int cnt=1000;
#define NUM 5


//等待之前，要对临界资源数量做判定，判定也是在访问资源，判定代码一定是在临界区内部
//所以判定结果也在临界区内部，条件不满足要休眠，一定是在临界区内部休眠的
void* threadrun(void* arg)
{
    std::string name=static_cast<char*>(arg);

    while(1)
    {
        pthread_mutex_lock(&glock);
        pthread_cond_wait(&gcond,&glock);//临界资源不满足导致等待，glock在wait之前，会自己释放掉
        std::cout<<"线程"<<name<<"计算"<<cnt<<std::endl;
        cnt++;
        pthread_mutex_unlock(&glock);

    }
}

int main()
{
    std::vector<pthread_t> threads;

    for(int i=0;i<NUM;i++)
    {
        char* name=new char[64];

        snprintf(name,64,"thread-%d",i);

        pthread_t tid;
        
        int n = pthread_create(&tid,NULL,threadrun,name);
        if(n!=0)
        {
            continue;
        }

        threads.push_back(tid);
        sleep(1);
    }

    while(1)
    {
        std::cout<<"唤醒一个线程"<<std::endl;
        pthread_cond_signal(&gcond);
        sleep(1);
    }

    for(auto& id:threads)
    {
        pthread_join(id,NULL);
    }

    return 0;
}